package com.wuseguang.springcloud.controller;

import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.JWTUtils;
import com.wuseguang.springcloud.util.MyDES;
import com.wuseguang.springcloud.util.Result;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @描述 学校管理平台登录
 * @创建人 zm
 * @创建时间 2020/5/4
 */
@RestController
public class AdminController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BaseTemplate baseTemplate;

    @RequestMapping("/alogin")
    public Result alogin(HttpServletResponse response,
                         @RequestParam("phone") String phone,
                         @RequestParam("pwd") String pwd) {
//判断手机号码是否为空
        if (StringUtils.isEmpty(phone)) {
            logger.info("mobile is null");
            return new Result(CodeUtil.MOBILE_IS_NULL);
        }
        //判断密码是否为空
        if (StringUtils.isEmpty(pwd)) {
            logger.info("pwd is null");
            return new Result(CodeUtil.PWD_IS_NULL);
        }
        String sql = "SELECT id,admin_name,phone,`password`,role,head_portrait,corporate_name  FROM school_admin WHERE phone=?";
        Map<String, Object> map = null;
        try {
            map = baseTemplate.queryMap(sql, phone);
        } catch (Exception e) {

        }

        if (map == null) {
            logger.info("user does not exist");
            return new Result(CodeUtil.USER_DOES_NOT_EXIST);
        }

        try {
            //判断密码是否正确
            if (!MyDES.decryptBasedDes(map.get("password").toString()).equals(pwd)) {
                logger.info("password error");
                return new Result(CodeUtil.PASSWORD_ERROR);
            }
        } catch (Exception e) {
            return new Result(CodeUtil.PASSWORD_ERROR);
        }
      /*  //管理员id
        paramMap.put("adminId", params[0]);
        //管理员账号
        paramMap.put("adminPhone", params[1]);
        //管理员名称
        paramMap.put("adminName", params[2]);
        //学校id
        paramMap.put("role", params[3]);*/
        String subject = String.format("%s-%s-%s-%s", map.get("id"), map.get("phone"), map.get("admin_name"), map.get("role"));
        //登录成功
        String token = Jwts.builder()
                .setSubject(subject)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JWTUtils.EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, JWTUtils.SIGNINGKEY)
                .compressWith(CompressionCodecs.DEFLATE)
                .compact();
        token = JWTUtils.ADMIN_PREFIX_VALIDATION + token;
        response.addHeader("token", token);
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("token", token);
        map.put("password", "");
        hm.put("admin", map);
        List<Map<String, Object>> list = baseTemplate.queryListMap("SELECT j.id,j.name FROM school_admin s,school_admin_jurisdiction j WHERE s.role=j.role AND s.id=?", map.get("id"));
        hm.put("roleList", list);
        return new Result(hm);
    }
}
